<template>
  <el-dialog
    v-model="dialogVisible"
    :title="!dialogParam.title ? '弹出框' : dialogParam.title"
    :destroy-on-close="true"
    :before-close="handleCancel"
    width="70%"
    @opened="handleOpened"
  >
    <div class="px-5 py-10">
      <el-row class="dialog-style">
        <el-col :span="12" class="dialog-style-left">
          <el-tabs v-model="data.activeName" type="card">
            <el-tab-pane
              v-for="(tab, index) in data.tabsOptions"
              :key="index"
              :label="tab.label"
              :name="tab.name"
              style="max-height: 55vh; overflow-y: auto"
            >
              <template v-if="tab.component == 'CustomTree'">
                <CustomTree
                  ref="CustomTreeRef"
                  @ok="getSelectData"
                  :componentOptions="tab.componentOptions"
                />
              </template>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="12" class="dialog-style-right">
          <div>已选数据</div>
          <el-divider style="margin: 5px 0" />
          <div v-for="(tab, index) in data.tabsOptions" :key="index">
            <template
              v-if="
                tab.componentOptions.selectData &&
                tab.componentOptions.selectData.length > 0
              "
            >
              <div class="flex items-center justify-between w-full">
                <div>{{ tab.label }}</div>
                <div class="mr-3">
                  <el-button
                    link
                    type="primary"
                    @click.stop="emptySelectData(tab.name, index)"
                    >清空</el-button
                  >
                </div>
              </div>
              <template
                v-if="
                  tab.componentOptions.selectData &&
                  tab.componentOptions.selectData.length > 0
                "
              >
                <el-tag
                  v-for="(tag, i) in tab.componentOptions.selectData"
                  :key="tag.itemValue"
                  closable
                  class="mr-2 mb-2"
                  :type="data.tagType[index % 5]"
                  @close="handleTagDel(tag, i, tab, index)"
                >
                  {{ tag.itemLabel }}
                </el-tag>
              </template>
            </template>
          </div>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleAffirm"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup name="SelectOrTreeDialog">
import { ElTree } from 'element-plus'
import { getCurrentInstance, nextTick, watchEffect } from 'vue'
import useCommonStore from '@/store/modules/common'
import CustomTree from './modules/CustomTree.vue'
const { proxy } = getCurrentInstance()
// 通用数据store
const commonStore = useCommonStore()
const components = shallowRef({
  CustomTree
})

// 接受父级传递的参数
const props = defineProps({
  dialogParam: {
    required: true,
    type: Object || Array,
    default: () => {
      return {}
    }
  },
  tabsOptionsData: {
    required: true,
    type: Array,
    default: () => {
      return []
    }
  }
})
const treeRef = ref(ElTree)
// 选中的数据
const selectData = ref([])
// 弹出框是否隐藏
const dialogVisible = ref(false)
// 总体结果是否多选
const resultMultiple = ref(false)

//设置参数
const dialogObj = reactive({
  // avue-tree 的数据
  checkStrictly: false, //是否遵循父子不互相关联的做法，默认为 false
  nodeKey: props.dialogParam.nodeKey || 'id' //值默认id
})

// 获取tabs配置数据
const data = reactive({
  activeName: '', //tabs modal
  tabsOptions: [], //
  collapseVal: [], //折叠面板
  tagType: {
    1: 'success',
    2: 'warning',
    3: 'danger',
    4: 'info',
    5: ''
  }
})
const handleOpened = () => {
  if (props.tabsOptionsData.length > 0) {
    proxy.$nextTick(() => {
      data.activeName = props.tabsOptionsData[0].name
    })
  }
}

// 搜索关键字
const filterText = ref('')
watch(filterText, val => {
  !treeRef.value.filter(val)
})
watchEffect(
  () => {
    // 获取tabs配置数据
    data.tabsOptions = props.tabsOptionsData
    if (props.tabsOptionsData.length > 0) {
      // 赋值折叠面板默认值
      props.tabsOptionsData.forEach(item => {
        if (
          item.componentOptions.selectData &&
          item.componentOptions.selectData.length > 0
        ) {
          if (data.collapseVal.indexOf(item.name) == -1) {
            data.collapseVal.push(item.name)
          }
        }
      })
      console.info('data.collapseVal', data.collapseVal)
    }
    dialogVisible.value = props.dialogParam.isDialog // 表单弹出框
    resultMultiple.value = props.dialogParam.resultMultiple // 总体结果是否多选
  },
  {
    flush: 'post'
  }
)

const emits = defineEmits(['ok', 'close', 'handleConfirm'])

/**
 * 清空选中的数据
 */
const emptySelectData = (name, index) => {
  // 删除抽屉name
  data.collapseVal.splice(data.collapseVal.indexOf(name), 1)
  // 清空选中数据
  data.tabsOptions[index].componentOptions.selectData = []
  // 清空树选中数据
  proxy.$refs['CustomTreeRef'][index].emptySelectData()
}

/**
 * 触发组件取消节点选中事件
 * @param tag 选中的tag
 * @param i 选中的tag的索引
 * @param tab 选中的tab数据
 * @param index 选中的tab的索引
 */
const handleTagDel = (tag, i, tab, index) => {
  tab.componentOptions.selectData.splice(i, 1)

  proxy.$refs['CustomTreeRef'][index].delNode(tag)
  if (tab.componentOptions.selectData.length == 0) {
    data.collapseVal.splice(data.collapseVal.indexOf(tab.name), 1)
  }
}
/**
 * 获取选中数据
 */
const getSelectData = result => {
  console.info('result', result)
  // 判断结果是否多选
  if (resultMultiple.value) {
    // 判断是否有数据如果有则展开折叠篮
    if (result.selectData.length > 0) {
      if (data.collapseVal.indexOf(result.dataType) == -1) {
        data.collapseVal.push(result.dataType)
      }
    } else {
      if (data.collapseVal.indexOf(result.dataType) == -1) {
        data.collapseVal.splice(data.collapseVal.indexOf(result.dataType), 1)
      }
    }
  } else {
    // 结果为单选
    // 清空其他选中数据
    data.tabsOptions.forEach((item, index) => {
      if (item.name != result.dataType) {
        emptySelectData(item.name, index)
      }
    })
    if (data.collapseVal.indexOf(result.dataType) == -1) {
      data.collapseVal.push(result.dataType)
    }
  }
  // 赋值选中数据
  data.tabsOptions.forEach(item => {
    if (item.name == result.dataType) {
      item.componentOptions = result
    }
  })
  console.info('data.tabsOptions', data.tabsOptions)
}

// 确认操作
const handleAffirm = () => {
  let resultArr = []
  data.tabsOptions.forEach(item => {
    if (
      !item.componentOptions.selectData ||
      item.componentOptions.selectData.length === 0
    )
      return
    let obj = {}
    obj.label = item.label
    obj.name = item.name
    obj.selectData = item.componentOptions.selectData
    console.info(1)
    resultArr.push(obj)
  })
  console.info('12213', data.tabsOptions)
  console.info('43242', resultArr)

  emits('handleConfirm', resultArr)
  handleCancel()
}
// 取消操作
const handleCancel = () => {
  data.tabsOptions = []
  dialogVisible.value = false
}

// 清空数据
const handleClear = () => {}
</script>
<style scoped lang="scss">
ul,
li {
  margin: 0;
  margin-block-end: 0;
  margin-block-start: 0;
}
.dialog-style {
  @apply mt--20px;
  .dialog-style-left {
    border-right: 1px solid #ccc;
    @apply pr-20px;
    .customNodeClass {
      :deep(.el-checkbox__inner) {
        @apply rounded-50;
      }
    }
  }
  .dialog-style-right {
    @apply leading-30px pl-20px  cursor-pointer;
    .clear {
      color: var(--el-color-primary);
      @apply text-right;
    }
  }
  .dialog-style-list {
    @apply mt-15px ml--40px  leading-20px;
    li {
      color: #999;
      background-color: #f5f5f5;
      @apply flex list-none pl-15px pt-5px pb-5px mb-10px rounded-35px;
      span {
        color: var(--el-color-primary);
        @apply flex-1 text-right pr-15px cursor-pointer;
      }
    }
  }
}
</style>
